//
//  WHChargeController.m
//  BinFengExpressOwner
//
//  Created by 邓伟浩 on 2018/11/1.
//  Copyright © 2018年 BinFeng. All rights reserved.
//

#import "WHChargeController.h"
#import "WHPayCell.h"
#import "WHPayTools.h"

@interface WHChargeController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *payTableView;

@property (nonatomic, strong) NSArray *tipsImageArray;
@property (nonatomic, strong) NSArray *tipsArray;
@property (nonatomic, strong) NSArray *descriptArray;

@property (nonatomic, assign) int currentSelectIndex;
@property (nonatomic, strong) NSURLSessionDataTask *payMoneyTask;

@end

@implementation WHChargeController

- (void)registerNotification {
    [kNotificationCenter addObserver:self
                            selector:@selector(payMoneySuccess:)
                                name:KPayMoneySuccess
                              object:nil];
}

- (void)payMoneySuccess:(NSNotification *)noti {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"充值";
    [self initParams];
    [self setUpPayTableView];
    [self registerNotification];
}

- (void)initParams {
    _currentSelectIndex = 0;
//    _tipsImageArray = @[@"share_WXChat_icon", @"pay_alipay"];
//    _tipsArray = @[@"微信支付", @"支付宝支付"];
//    _descriptArray = @[@"免手续费", @"免手续费"];
    _tipsImageArray = @[@"pay_alipay"];
    _tipsArray = @[@"支付宝支付"];
    _descriptArray = @[@"免手续费"];
}

- (void)setUpPayTableView {
    UITableView *payTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:payTableView];
    payTableView.delegate = self;
    payTableView.dataSource = self;
    payTableView.tableHeaderView = [self tableHeaderView];
    payTableView.tableFooterView = [self tableFooterView];
    payTableView.backgroundColor = CViewBgMainColor;
    payTableView.separatorColor = CLineColor;
    payTableView.separatorInset = UIEdgeInsetsMake(0, kRealwidth(15), 0, kRealwidth(15));
    ViewRadius(payTableView, 10);
    
    [payTableView registerClass:[WHPayCell class] forCellReuseIdentifier:NSStringFromClass([WHPayCell class])];
    
    [payTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(kTopHeight);
    }];
    
    _payTableView = payTableView;
}

- (UIView *)tableHeaderView {
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(60));
    tableHeaderView.backgroundColor = CViewBgMainColor;
    ViewBorderRadius(tableHeaderView, 0, 0.5, CLineColor);
    
    UIView *backContentView = [[UIView alloc] init];
    [tableHeaderView addSubview:backContentView];
    backContentView.backgroundColor = KWhiteColor;
    backContentView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(55));
    ViewBorderRadius(backContentView, 0, 0.5, CLineColor);
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    [backContentView addSubview:tipsLabel];
    tipsLabel.textColor = CFontTitleBlackColor;
    tipsLabel.font = SYSTEMFONT(kRealwidth(16));
    tipsLabel.text = NSStringFormat(@"￥ %@", self.chargeModel.money);
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(backContentView.mas_centerY);
        make.height.mas_equalTo(kRealwidth(16));
        make.left.mas_equalTo(kRealwidth(15));
    }];
    
    return tableHeaderView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(85));
    tableFooterView.backgroundColor = CViewBgMainColor;
    
    
    UIButton *payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:payButton];
    payButton.frame = CGRectMake(kRealwidth(32), kRealwidth(20), KScreenWidth-2*kRealwidth(32), kRealwidth(45));
    NSString *payStr = @"确认支付";
    NSAttributedString *payAttributeStr = [[NSAttributedString alloc] initWithString:payStr attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [payButton setAttributedTitle:payAttributeStr forState:UIControlStateNormal];
    payButton.backgroundColor = CMDarkOrangeColor;
    ViewRadius(payButton, kRealwidth(45)/2);
    [payButton addTarget:self action:@selector(doPay:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFooterView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _tipsImageArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHPayCell *payCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHPayCell class]) forIndexPath:indexPath];
    payCell.tipsImageView.image = IMAGE_NAMED(_tipsImageArray[indexPath.row]);
    payCell.tipsLabel.text = _tipsArray[indexPath.row];
    payCell.descriptionLabel.text = _descriptArray[indexPath.row];
    if (indexPath.row == _currentSelectIndex) {
        payCell.rightButtonSelect = YES;
    } else {
        payCell.rightButtonSelect = NO;
    }
    
    if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section] - 1) {
        [payCell updateLine:YES];
    } else {
        [payCell updateLine:NO];
    }
    
    
    return payCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(74);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.currentSelectIndex = (int)indexPath.row;
    [self.payTableView reloadData];
}

#pragma mark - —————— UITextFieldDelegate ——————

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *str = NSStringFormat(@"%@%@", textField.text, string);
    return [WHValidationHelper validateMoney:str];
}

#pragma mark - —————— 事件 ——————

- (void)doPay:(UIButton *)button {
    [self.view endEditing:YES];
    if (self.currentSelectIndex == -1) {
        [WHView showHudMsg:@"请选择支付方式"];
        return;
    }
    double totalAmount = self.chargeModel.money.doubleValue;
    
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_insertMessageRecharge);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          self.chargeModel.id, @"smsId",
                          @(2), @"payType", // 支付类型（1：微信，2：支付宝)
                          nil];
    
    if (self.currentSelectIndex == 0) {
        _payMoneyTask = [WHPayTools alipyWithUrl:postURL parameters:dict money:totalAmount];
    }
//    if (self.currentSelectIndex == 0) {
//        _payMoneyTask = [WHPayTools WXPayWithUrl:postURL parameters:dict appKey:kWXAppKey];
//    }
}

#pragma mark - —————— 接口 ——————

- (void)backBtnClicked {
    [super backBtnClicked];
    if (_payMoneyTask) {
        [_payMoneyTask cancel];
        _payMoneyTask = nil;
    }
}

@end
